<template>
  <div  style="background-color:hotpink"
    class="drag-item"
    :style="{
      width: `${item.width}px`,
      height: `${item.height}px`,
    }"
  >
    <div class="drag-handle"></div>
    <div class="drag-content" style="background-color:bisque">
      {{ item.content }}
    </div>
    <div class="resize-handle" @mousedown.stop="startResize">1</div>
    <el-button
      class="delete-btn"
      type="danger"
      :icon="Delete"
      circle
      size="small"
      @click.stop="$emit('delete')"
    />
  </div>
</template>

<script setup lang="ts">
import { Delete } from '@element-plus/icons-vue'
import { PropType } from 'vue'

const props = defineProps({
  item: {
    type: Object as PropType<{
      id: string
      x: number
      y: number
      width: number
      height: number
      content: string
    }>,
    required: true
  }
})

const emit = defineEmits(['delete', 'update'])

let startX = 0
let startY = 0
let isResizing = false

const startResize = (e: MouseEvent) => {
  isResizing = true
  startX = e.clientX
  startY = e.clientY
  const startWidth = props.item.width
  const startHeight = props.item.height
  document.addEventListener('mousemove', (e) => handleResize(e, startWidth, startHeight))
  document.addEventListener('mouseup', stopResize)
}

const handleResize = (e: MouseEvent, startWidth: number, startHeight: number) => {
  if (!isResizing) return
  const newWidth = Math.max(50, startWidth + (e.clientX - startX))
  const newHeight = Math.max(50, startHeight + (e.clientY - startY))
  const newItem = {
    ...props.item,
    width: newWidth,
    height: newHeight
  }
  emit('update', newItem)
}

const stopResize = () => {
  isResizing = false
  document.removeEventListener('mousemove', handleResize)
  document.removeEventListener('mouseup', stopResize)
}

</script>

<style scoped>
.drag-item {
  position: relative;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  user-select: none;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin: 10px;
  transition: transform 0.2s, box-shadow 0.2s;
}

.drag-item:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
}

.drag-handle {
  position: absolute;
  left: 0px;
  top: 0%;
  transform: translateY(-50%);
  width: 12px;
  height: 12px;
  background-color: rgba(168, 24, 24, 0.7);
  border-radius: 50%;
  cursor: move;
}

.drag-content {
  padding: 10px;
  width: calc(100% - 30px);
  text-align: center;
}

.resize-handle {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 12px;
  height: 12px;
  background-color: rgba(255, 255, 255, 0.7);
  cursor: nwse-resize;
  border-radius: 2px;
  opacity: 0;
  transition: opacity 0.2s;
}

.delete-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  z-index: 100;
  opacity: 0;
  transition: opacity 0.2s;
}

.drag-item:hover .delete-btn,
.drag-item:hover .resize-handle {
  opacity: 1;
}
</style>